package com.you.raft;


import com.you.raft.common.entity.NodeConfig;
import com.you.raft.core.RaftNode;
import com.you.raft.core.impl.DefaultRaftNode;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

import static com.you.raft.config.SystemConstant.*;

@Slf4j
public class RaftNodeStarter {

    public static void main(String[] args) throws Exception {
        //==============测试使用===============
        System.setProperty(CLUSTER_LIST, "localhost:10001,localhost:10002,localhost:10003");
        System.setProperty(SERVER_PORT, "10001");
        //==============启动程序===============
        start();
    }

    public static void start() throws Exception {
        //获取节点参数
        int selfPort = Integer.valueOf(System.getProperty(SERVER_PORT));
        List<String> allAddresses = Arrays.asList(System.getProperty(CLUSTER_LIST).split(","));
        //设置节点配置端口
        NodeConfig config = new NodeConfig();
        config.setSelfPort(selfPort);
        config.setAllNodeAddresses(allAddresses);
        //启动节点
        RaftNode raftNode = DefaultRaftNode.getInstance();
        raftNode.init(config);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            synchronized (raftNode) {
                raftNode.notifyAll();
            }
        }));
        synchronized (raftNode) {
            raftNode.wait();
        }
        log.info("===========");
        raftNode.destory();
    }

}
